import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import BadData

from apps.users.models import User

'''
我们需要的需求是用户名或手机号登陆，系统默认提供的用户名登陆
当系统的类、方法不能满足需求时，继承重写

'''

def get_user_by_username(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            user = User.objects.get(mobile=username)

        else:
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    return user

class UsernameMobileModelBackend(ModelBackend):


    def authenticate(self,request,username=None,password=None,**kwargs):


        user= get_user_by_username(username)

        if user is not None and user.check_password(password):
            return user

from itsdangerous import  TimedJSONWebSignatureSerializer as Serializer

from meiduo_mall import  settings

def generic_verify_email_url(user_id):

    s = Serializer(secret_key= settings.SECRET_KEY,expires_in=3600)
    data = {
        'user_id':user_id,

    }
    #加密
    token = s.dumps(data)

    return settings.EMAIL_VERIFY_URL + '?token=' + token.decode()

def check_verify_email_token(token):

    s = Serializer(secret_key= settings.SECRET_KEY,expires_in=3600)
    try:
        result = s.loads(token)
    except BadData :
        return None

    return result.get('user_id')